package com.rede.didiok.user.modulelist.rank.restapi;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.rede.didiok.common.annotion.AvoidRepeatableCommit.AvoidRepeatableCommit;
import com.rede.didiok.common.annotion.PublishLimitVerify.PublishLimitVerify;
import com.rede.didiok.common.annotion.SubmitVerify.SubmitVerify;
import com.rede.didiok.common.annotion.checkRegexVerify.CheckRegexVerify;
import com.rede.didiok.common.annotion.log.BussinessLog;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.rank.*;
import com.rede.didiok.common.enums.*;
import com.rede.didiok.common.exception.ThrowableUtils;
import com.rede.didiok.common.exception.exceptionType.QueryException;
import com.rede.didiok.common.feign.AdminFeignClient;
import com.rede.didiok.common.holder.RequestHolder;
import com.rede.didiok.common.utils.ResultUtil;
import com.rede.didiok.common.utils.StringUtils;
import com.rede.didiok.common.validator.group.Default;
import com.rede.didiok.common.validator.group.Delete;
import com.rede.didiok.common.validator.group.GetList;
import com.rede.didiok.user.modulelist.rank.entity.RankMemberEntity;
import com.rede.didiok.user.modulelist.rank.service.*;

/**
 * 博客创作相关
 *
 * @author: Rede
 * @create: 2024-07-11-9:58
 */
@RestController
@RefreshScope
@RequestMapping("/createRankMember")
@Api(value = "榜单成员创作相关接口", tags = {"榜单成员创作相关接口"})
@Slf4j
public class CreateRankMemberRestApi {

    @Autowired
    private RankMemberService rankMemberService;
    @Autowired
    private RankCategoryService rankCategoryService;
    @Autowired
    private MemberTagService memberTagService;
    @Autowired
    private MemberGradeService memberGradeService;
    @Autowired
    private RankService rankService;
    @Autowired
    private AdminFeignClient adminFeignClient;

    @ApiOperation(value = "获取用户的榜单成员列表", notes = "获取用户的榜单成员列表", response = String.class)
    @PostMapping("/getUserRankMemberList")
    public String getUserRankMemberList(@Validated({GetList.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {

        ThrowableUtils.checkParamArgument(result);
        return ResultUtil.successWithData(rankMemberService.getPageListWithPicAndRank(rankMemberDto));
    }

    @ApiOperation(value = "获取当前用户的榜单成员列表", notes = "获取用户的榜单成员列表", response = String.class)
    @PostMapping("/getMeRankMemberList")
    public String getMeRankMemberList(HttpServletRequest request, @Validated({GetList.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {
        String userUid = RequestHolder.getUserUid();
        if (StringUtils.isEmpty(userUid)) {
            throw new QueryException(Constants.USER_UID_EMPTY);
        }
        // 前端没有传递用户UID时，将查询在线用户的博客列表
        rankMemberDto.setCreateUserUid(userUid);
        ThrowableUtils.checkParamArgument(result);
        return ResultUtil.successWithData(rankMemberService.getPageListWithPicAndRank(rankMemberDto));
    }

    @ApiOperation(value = "获取当前用户的榜单成员列表（电脑端）", notes = "获取用户的榜单成员列表", response = String.class)
    @PostMapping("/getMeRankMemberListPC")
    public String getMeRankMemberListPC(HttpServletRequest request, @Validated({GetList.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {
        String userUid = RequestHolder.getUserUid();
        if (StringUtils.isEmpty(userUid)) {
            throw new QueryException(Constants.USER_UID_EMPTY);
        }
        // 前端没有传递用户UID时，将查询在线用户的博客列表
        rankMemberDto.setCreateUserUid(userUid);
        ThrowableUtils.checkParamArgument(result);
        return ResultUtil.successWithData(rankMemberService.getPageListWithPicAndRankPC(rankMemberDto));
    }


    @CheckRegexVerify(behavior = RegexTypeEnum.RANK_MEMBER_PUBLISH)
    @PublishLimitVerify(behavior = PublishLimitTypeEnum.RANK_MEMBER_COUNT)
    @SubmitVerify
    @BussinessLog(value = "增加榜单成员", behavior = BehaviorEnum.ADD_RANK_MEMBER)
    @AvoidRepeatableCommit
    @ApiOperation(value = "增加榜单成员", notes = "增加榜单成员", response = String.class)
    @PostMapping("/add")
    public String add(@Validated({Default.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {

//        // 判断是否开启投稿功能
//        R configResult = adminFeignClient.getWebConfig();
//        WebConfigDto webConfig = null;
//        if (configResult.getCode() == 0) {
//            webConfig = configResult.getData(new TypeReference<WebConfigDto>(){});
//        }else {
//            throw new FeignException("feign调用异常（获取网站配置）：失败");
//        }
//        if (Constants.STR_ZERO.equals(webConfig.getOpenCreateRankMember())) {
//            return ResultUtil.errorWithMessage("后台暂未开启投稿功能");
//        }
        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        // 文章类型只能是博客类型
        rankMemberDto.setType(Constants.STR_ZERO);
        // 推荐类型默认为正常
        rankMemberDto.setLevel(LevelEnum.NORMAL);
        rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
        rankMemberDto.setOpenLoadingValid(Integer.valueOf(OpenStatusEnum.CLOSE));
        return rankMemberService.addRankMemberByUser(rankMemberDto);
    }


    @BussinessLog(value = "编辑榜单成员", behavior = BehaviorEnum.EDIT_RANK_MEMBER)
    @AvoidRepeatableCommit
    @ApiOperation(value = "编辑榜单成员", notes = "编辑榜单成员", response = String.class)
    @PostMapping("/edit")
    public String edit(@Validated({Default.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {
        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
        // HERE
        return rankMemberService.editRankMemberByUser(rankMemberDto);
    }

    @BussinessLog(value = "发布/下架榜单成员", behavior = BehaviorEnum.PUBLISH_RANK_MEMBER)
    @AvoidRepeatableCommit
    @ApiOperation(value = "发布/下架榜单成员", notes = "发布/下架榜单成员", response = String.class)
    @PostMapping("/publish")
    public String publish(@RequestBody RankMemberDto rankMemberDto) {
        rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
        return rankMemberService.publishByUser(rankMemberDto);
    }

    @BussinessLog(value = "将活动取消/恢复正常", behavior = BehaviorEnum.PUBLISH_RANK_MEMBER)
    @AvoidRepeatableCommit
    @ApiOperation(value = "将活动取消/恢复正常", notes = "将活动取消/恢复正常", response = String.class)
    @PostMapping("/activityStatus/change")
    public String changeActivityStatus(@RequestBody RankMemberDto rankMemberDto) {
        rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
        return rankMemberService.changeActivityStatus(rankMemberDto);
    }

    @BussinessLog(value = "删除榜单成员", behavior = BehaviorEnum.DELETE_RANK_MEMBER)
    @AvoidRepeatableCommit
    @ApiOperation(value = "删除榜单成员", notes = "删除榜单成员", response = String.class)
    @PostMapping("/delete")
    public String delete(@Validated({Delete.class}) @RequestBody RankMemberDto rankMemberDto, BindingResult result) {
        String userUid = RequestHolder.getUserUid();
        if (StringUtils.isEmpty(userUid)) {
            throw new QueryException(Constants.USER_UID_EMPTY);
        }
//        if (StringUtils.isEmpty(userUid)) {
//            return ResultUtil.errorWithMessage("登录后才可以删除榜单成员！");
//        }
        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        rankMemberDto.setRankMemberSource(ContributeSourceEnum.USER_PUBLISH);
        return rankMemberService.deleteRankMemberByUser(rankMemberDto);
    }

    @ApiOperation(value = "获取榜单分类列表", notes = "获取榜单分类列表", response = String.class)
    @PostMapping("/getRankCategoryList")
    public String getRankCategoryList(@Validated({GetList.class}) @RequestBody RankCategoryDto rankCategoryDto, BindingResult result) {

        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        log.info("获取榜单分类列表");
        return ResultUtil.successWithData(rankCategoryService.getPageList(rankCategoryDto));
    }

    @ApiOperation(value = "获取榜单列表", notes = "获取榜单列表", response = String.class)
    @PostMapping("/getRankList")
    public String getRankList(@Validated({GetList.class}) @RequestBody RankDto rankDto, BindingResult result) {

        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        log.info("获取榜单分类列表");
        return ResultUtil.successWithData(rankService.getPageList(rankDto));
    }

    @ApiOperation(value = "获取报名费支付方式列表", notes = "获取报名费支付方式列表", response = String.class)
    @GetMapping("/getPayMethodList")
    public String getPayMethodList() {

        log.info("获取报名费支付方式列表");
        List<PayMethodDto> list = new ArrayList<>();
        for (PayMethodEnum method : PayMethodEnum.values()) {
            if (method.getType() > 10 ) {
                PayMethodDto payMethodDto = new PayMethodDto(method.getName(), method.getType());
                list.add(payMethodDto);
            }
        }
        return ResultUtil.successWithData(list);
    }


    /**
     * 获取标签列表
     * @param tagVO
     * @param result
     * @return
     */
    @ApiOperation(value = "获取标签列表", notes = "获取标签列表", response = String.class)
    @PostMapping("/getMemberTagList")
    public String getMemberTagList(@Validated({GetList.class}) @RequestBody MemberTagDto tagVO, BindingResult result) {
        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        log.info("获取标签列表");
        return ResultUtil.result(SysConf.SUCCESS, memberTagService.getPageList(tagVO));
    }

    @ApiOperation(value = "获取榜单列表", notes = "获取榜单列表", response = String.class)
    @PostMapping("/getMemberGradeList")
    public String getList(@Validated({GetList.class}) @RequestBody MemberGradeDto gradeDto, BindingResult result) {

        // 参数校验
        ThrowableUtils.checkParamArgument(result);
        log.info("获取榜单列表");
        return ResultUtil.result(SysConf.SUCCESS, memberGradeService.getPageList(gradeDto));
    }

    @ApiOperation(value = "随机一文", notes = "随机一文", response = String.class)
    @PostMapping("/randomRankMember")
    public String randomRankMember() {
        log.info("随机一文");
        return ResultUtil.successWithData(rankMemberService.randomRankMember());
    }

    /**
     * 查询文章发表积分榜
     * @return
     */
    @ApiOperation(value = "查询文章发表积分榜", notes = "查询文章发表积分榜")
    @GetMapping(value = "/getLeaderRankMember")
    public String getLeaderRankMember(@ApiParam(name = "refresh", value = "是否刷新配置", required = false) @RequestParam(name = "refresh", required = false, defaultValue = "false") Boolean refresh) {
        List<RankMemberEntity> leaderWeek = rankMemberService.getLeaderRankMember(refresh);
        return ResultUtil.result(SysConf.SUCCESS, leaderWeek);
    }
}
